package com.zzwtec.androidtest;

import android.util.Log;

import java.io.BufferedOutputStream;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.LineNumberReader;
import java.net.Socket;
import java.security.cert.CertificateException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.atomic.AtomicInteger;

import javax.net.ssl.SSLSocketFactory;
import javax.net.ssl.X509TrustManager;

public class Test implements Runnable {
    private static final String SEQUENCE = "\r\n";
    private final String serverUrl = "api.zzwtec.com";
    private final int serverPort = 443;

    private static X509TrustManager trustAllCert = new X509TrustManager() {
        @Override
        public void checkClientTrusted(java.security.cert.X509Certificate[] chain, String authType) throws CertificateException {
        }

        @Override
        public void checkServerTrusted(java.security.cert.X509Certificate[] chain, String authType) throws CertificateException {
        }

        @Override
        public java.security.cert.X509Certificate[] getAcceptedIssuers() {
            return new java.security.cert.X509Certificate[]{};
        }
    };
    private static SSLSocketFactory socketFactory = new TLSSocketFactory(trustAllCert);

    private static ExecutorService executor;
    private static AtomicInteger times = new AtomicInteger(0);

    public static void test(){
        ExecutorService executor = Executors.newFixedThreadPool(20);
        Log.d("Test", "start");
        while(times.get() < 10000){
            executor.execute(new Test());
            times.incrementAndGet();
        }
        Log.d("Test", "add end");
    }

    @Override
    public void run() {
        try{
//            int timeout = 60 * 1000;
            Socket sslSocket = socketFactory.createSocket(serverUrl, serverPort);
//            sslSocket.setSoTimeout(timeout);
            BufferedOutputStream sslOutput = new BufferedOutputStream(sslSocket.getOutputStream());

            StringBuilder sb = new StringBuilder();
            /**
             * 请求方法|空格|URL|空格|协议版本|回车符|换行符
             * 头部字段名|:|值|回车符|换行符
             * ...
             * 头部字段名|:|值|回车符|换行符
             * 回车符|换行符
             * 请求数据
             */
            String body = "{\"requestId\":\"test\",\"doorType\":\"1\",\"mac\":\"2e:1b:98:8e:13:b6\",\"isWifi\":\"0\",\"bluetooth\":\"22:22:87:B3:22:82\"}";
            sb.append("POST /device/init HTTP/1.1").append(SEQUENCE); // 请求行
            sb.append("Host:").append(serverUrl).append(SEQUENCE);
            sb.append("Content-Type:application/json;charset=UTF-8").append(SEQUENCE);
            sb.append("Content-Length:").append(body.length()).append(SEQUENCE);
            sb.append(SEQUENCE);
            sb.append(body);
            String request = sb.toString();
//            Log.d("Test", "request:"+times.get()+" "+request);
            byte[] data = request.getBytes();
            sslOutput.write(data, 0, data.length);
            sslOutput.flush();

            InputStream is = sslSocket.getInputStream();
            LineNumberReader lnr = new LineNumberReader(new InputStreamReader(is));
            StringBuffer headRes = new StringBuffer();
            StringBuffer contentRes = new StringBuffer();
            String line = null;
            boolean isBody = false;
            do {
                line = lnr.readLine();
                if(line==null){
                    break;
                }
                if(isBody){
                    contentRes.append(line + SEQUENCE);
                }else{
                    headRes.append(line + SEQUENCE);
                }
                if(line.equals("")){
                    isBody = true;
                }
                // 由于LineNumberReader会把\r\n替换掉，所以如果读到一行为""证明http head结束
            } while (line!=null);

            Log.d("Test", "response:"+times.get()+" "+headRes.toString()+contentRes.toString());
            sslSocket.close();
        }catch (Exception e){
            e.printStackTrace();
        }
        times.decrementAndGet();
        if(times.get() <= 0){
            Log.d("Test", "over");
        }
    }

}
